<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>Spring源码系列-第9章-SpringMVC请求处理源码和HandlerMapping原理 | 风祈的时光录</title><meta name="keywords" content="Spring，框架，spring源码"><meta name="author" content="youthlql"><meta name="copyright" content="youthlql"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="SpringMVC请求处理源码和HandlerMapping原理">
<meta property="og:type" content="article">
<meta property="og:title" content="Spring源码系列-第9章-SpringMVC请求处理源码和HandlerMapping原理">
<meta property="og:url" content="https://imlql.cn/post/6f2cef28.html">
<meta property="og:site_name" content="风祈的时光录">
<meta property="og:description" content="SpringMVC请求处理源码和HandlerMapping原理">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://npm.elemecdn.com/lql_static@latest/logo/spring.png">
<meta property="article:published_time" content="2022-06-21T04:01:02.000Z">
<meta property="article:modified_time" content="2022-07-24T11:22:15.033Z">
<meta property="article:author" content="youthlql">
<meta property="article:tag" content="Spring源码">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://npm.elemecdn.com/lql_static@latest/logo/spring.png"><link rel="shortcut icon" href="https://npm.elemecdn.com/youthlql@1.0.8/blog/favicon.png"><link rel="canonical" href="https://imlql.cn/post/6f2cef28"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//hm.baidu.com"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://npm.elemecdn.com/@fortawesome/fontawesome-free@6/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://npm.elemecdn.com/@fancyapps/ui/dist/fancybox.css" media="print" onload="this.media='all'"><script>var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?f693ff99cc7e613b88cf5b729a14b48b";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery@2/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery@2/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isAnchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'Spring源码系列-第9章-SpringMVC请求处理源码和HandlerMapping原理',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2022-07-24 19:22:15'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><link rel="stylesheet" href="https://npm.elemecdn.com/lql_static@latest/butterfly_static/css/ali_icon.css"><link rel="stylesheet" href="https://npm.elemecdn.com/lql_static@latest/butterfly_static/css/2-24-mogai.css"><meta name="generator" content="Hexo 5.4.0"><link rel="alternate" href="/atom.xml" title="风祈的时光录" type="application/atom+xml">
</head><body><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/avatar/2.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data is-center"><div class="data-item"><a href="/archives/"><div class="headline">文章</div><div class="length-num">37</div></a></div><div class="data-item"><a href="/tags/"><div class="headline">标签</div><div class="length-num">21</div></a></div><div class="data-item"><a href="/categories/"><div class="headline">分类</div><div class="length-num">13</div></a></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw iconfont icon-shouyex"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw iconfont icon-zuixinwenzhang_huaban"></i><span> 找文章</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/categories/"><i class="fa-fw iconfont icon-fenlei1"></i><span> 分类</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw iconfont icon-biaoqian1"></i><span> 标签</span></a></li><li><a class="site-page child" href="/archives/"><i class="fa-fw iconfont icon-shijianzhou"></i><span> 归档</span></a></li></ul></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://npm.elemecdn.com/lql_static@latest/logo/spring.png')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">风祈的时光录</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw iconfont icon-shouyex"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw iconfont icon-zuixinwenzhang_huaban"></i><span> 找文章</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/categories/"><i class="fa-fw iconfont icon-fenlei1"></i><span> 分类</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw iconfont icon-biaoqian1"></i><span> 标签</span></a></li><li><a class="site-page child" href="/archives/"><i class="fa-fw iconfont icon-shijianzhou"></i><span> 归档</span></a></li></ul></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">Spring源码系列-第9章-SpringMVC请求处理源码和HandlerMapping原理</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2022-06-21T04:01:02.000Z" title="发表于 2022-06-21 12:01:02">2022-06-21</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2022-07-24T11:22:15.033Z" title="更新于 2022-07-24 19:22:15">2022-07-24</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Spring/">Spring</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Spring/%E6%BA%90%E7%A0%81V1/">源码V1</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">4.4k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>20分钟</span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="第9章-SpringMVC请求处理源码和HandlerMapping原理"><a href="#第9章-SpringMVC请求处理源码和HandlerMapping原理" class="headerlink" title="第9章-SpringMVC请求处理源码和HandlerMapping原理"></a>第9章-SpringMVC请求处理源码和HandlerMapping原理</h1><h2 id="请求的处理链路"><a href="#请求的处理链路" class="headerlink" title="请求的处理链路"></a>请求的处理链路</h2><img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_09/image-20211017194744212.png"/>

<ol>
<li>tomcat里面可以部署多个项目应用。/abc_test和mvc_test这种就是项目路径，用于区分多个项目</li>
<li>在以前的Servlet开发中，每一个路径都需要有一个Servlet来处理。比如上图所画</li>
<li>有了SpringMVC，整个Tomcat下面就不会有很多Servlet了，只会有一个DispatcherServlet来统一处理</li>
</ol>
<h3 id="Servlet继承树"><a href="#Servlet继承树" class="headerlink" title="Servlet继承树"></a>Servlet继承树</h3><img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_09/image-20211017195927505.png"/>



<ol>
<li>Servlet里是Service()方法处理请求</li>
<li>GenericServlet也是Service()方法处理请求</li>
<li>HttpServlet开始根据请求类型将处理方法分为doGet，doPost，doPut，doDelete等等</li>
<li>HttpServletBean没有处理方法</li>
<li>FrameworkServlet也是有处理方法分别为doGet，doPost，doPut，doDelete等等，但是这些方法最终调用的都是<code>processRequest(HttpServletRequest request, HttpServletResponse response)</code></li>
<li>DispatcherServlet处理方法是doService()</li>
</ol>
<h3 id="Debug调用栈"><a href="#Debug调用栈" class="headerlink" title="Debug调用栈"></a>Debug调用栈</h3><img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_09/image-20211017205544154.png" />

<h3 id="DispatcherServlet-doService"><a href="#DispatcherServlet-doService" class="headerlink" title="DispatcherServlet#doService()"></a>DispatcherServlet#doService()</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">doService</span><span class="params">(HttpServletRequest request, HttpServletResponse response)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">   logRequest(request);</span><br><span class="line"></span><br><span class="line">   <span class="comment">// Keep a snapshot of the request attributes in case of an include,</span></span><br><span class="line">   <span class="comment">// to be able to restore the original attributes after the include.</span></span><br><span class="line">   Map&lt;String, Object&gt; attributesSnapshot = <span class="keyword">null</span>; <span class="comment">//把request域的所有属性提前保存</span></span><br><span class="line">   <span class="keyword">if</span> (WebUtils.isIncludeRequest(request)) &#123;</span><br><span class="line">      attributesSnapshot = <span class="keyword">new</span> HashMap&lt;&gt;();</span><br><span class="line">      Enumeration&lt;?&gt; attrNames = request.getAttributeNames();</span><br><span class="line">      <span class="keyword">while</span> (attrNames.hasMoreElements()) &#123;</span><br><span class="line">         String attrName = (String) attrNames.nextElement();</span><br><span class="line">         <span class="keyword">if</span> (<span class="keyword">this</span>.cleanupAfterInclude || attrName.startsWith(DEFAULT_STRATEGIES_PREFIX)) &#123;</span><br><span class="line">            attributesSnapshot.put(attrName, request.getAttribute(attrName)); <span class="comment">//快照所有属性</span></span><br><span class="line">         &#125;</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="comment">//基本的东西保存到request域中方便处理 Make framework objects available to handlers and view objects.</span></span><br><span class="line">   request.setAttribute(WEB_APPLICATION_CONTEXT_ATTRIBUTE, getWebApplicationContext());</span><br><span class="line">   request.setAttribute(LOCALE_RESOLVER_ATTRIBUTE, <span class="keyword">this</span>.localeResolver); <span class="comment">//国际化解析器</span></span><br><span class="line">   request.setAttribute(THEME_RESOLVER_ATTRIBUTE, <span class="keyword">this</span>.themeResolver); <span class="comment">//主题解析器</span></span><br><span class="line">   request.setAttribute(THEME_SOURCE_ATTRIBUTE, getThemeSource());</span><br><span class="line"></span><br><span class="line">   <span class="keyword">if</span> (<span class="keyword">this</span>.flashMapManager != <span class="keyword">null</span>) &#123; <span class="comment">//闪存管理器（重定向携带数据）</span></span><br><span class="line">      FlashMap inputFlashMap = <span class="keyword">this</span>.flashMapManager.retrieveAndUpdate(request, response);</span><br><span class="line">      <span class="keyword">if</span> (inputFlashMap != <span class="keyword">null</span>) &#123;</span><br><span class="line">         request.setAttribute(INPUT_FLASH_MAP_ATTRIBUTE, Collections.unmodifiableMap(inputFlashMap));</span><br><span class="line">      &#125;</span><br><span class="line">      request.setAttribute(OUTPUT_FLASH_MAP_ATTRIBUTE, <span class="keyword">new</span> FlashMap());</span><br><span class="line">      request.setAttribute(FLASH_MAP_MANAGER_ATTRIBUTE, <span class="keyword">this</span>.flashMapManager);</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   RequestPath previousRequestPath = <span class="keyword">null</span>;</span><br><span class="line">   <span class="keyword">if</span> (<span class="keyword">this</span>.parseRequestPath) &#123;</span><br><span class="line">      previousRequestPath = (RequestPath) request.getAttribute(ServletRequestPathUtils.PATH_ATTRIBUTE);</span><br><span class="line">      ServletRequestPathUtils.parseAndCache(request);</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="keyword">try</span> &#123;</span><br><span class="line">      doDispatch(request, response); <span class="comment">//处理派发功能</span></span><br><span class="line">   &#125;</span><br><span class="line">   <span class="keyword">finally</span> &#123;</span><br><span class="line">      <span class="keyword">if</span> (!WebAsyncUtils.getAsyncManager(request).isConcurrentHandlingStarted()) &#123;</span><br><span class="line">         <span class="comment">// Restore the original attribute snapshot, in case of an include.</span></span><br><span class="line">         <span class="keyword">if</span> (attributesSnapshot != <span class="keyword">null</span>) &#123;</span><br><span class="line">            restoreAttributesAfterInclude(request, attributesSnapshot);</span><br><span class="line">         &#125;</span><br><span class="line">      &#125;</span><br><span class="line">      ServletRequestPathUtils.setParsedRequestPath(previousRequestPath, request);</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="DispatcherServlet-doDispatch-请求派发"><a href="#DispatcherServlet-doDispatch-请求派发" class="headerlink" title="DispatcherServlet#doDispatch()请求派发"></a>DispatcherServlet#doDispatch()请求派发</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//SpringMVC处理请求的核心流程</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">doDispatch</span><span class="params">(HttpServletRequest request, HttpServletResponse response)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">   HttpServletRequest processedRequest = request;</span><br><span class="line">   HandlerExecutionChain mappedHandler = <span class="keyword">null</span>; <span class="comment">//handler（目标方法）的执行链</span></span><br><span class="line">   <span class="keyword">boolean</span> multipartRequestParsed = <span class="keyword">false</span>; <span class="comment">//文件上传标志</span></span><br><span class="line">   <span class="comment">//对异步请求的支持（Servlet3.0以后才有的，Webflux）</span></span><br><span class="line">   WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);</span><br><span class="line"></span><br><span class="line">   <span class="keyword">try</span> &#123;</span><br><span class="line">      ModelAndView mv = <span class="keyword">null</span>;</span><br><span class="line">      Exception dispatchException = <span class="keyword">null</span>;</span><br><span class="line"></span><br><span class="line">      <span class="keyword">try</span> &#123;</span><br><span class="line">         processedRequest = checkMultipart(request); <span class="comment">//检查当前是否文件上传请求</span></span><br><span class="line">         multipartRequestParsed = (processedRequest != request);</span><br><span class="line"></span><br><span class="line">         <span class="comment">//构造出了【目标方法+拦截器整个链路】决定使用哪个Handler处理当前请求 Determine handler for the current request.</span></span><br><span class="line">         mappedHandler = getHandler(processedRequest);</span><br><span class="line">         <span class="keyword">if</span> (mappedHandler == <span class="keyword">null</span>) &#123;  <span class="comment">//如果找不到人处理，就send 404</span></span><br><span class="line">            noHandlerFound(processedRequest, response);</span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line">         &#125;</span><br><span class="line"></span><br><span class="line">         <span class="comment">//适配器怎么找的、 Determine handler adapter for the current request.</span></span><br><span class="line">         HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());</span><br><span class="line"></span><br><span class="line">         <span class="comment">// Process last-modified header, if supported by the handler.</span></span><br><span class="line">         String method = request.getMethod();</span><br><span class="line">         <span class="keyword">boolean</span> isGet = <span class="string">&quot;GET&quot;</span>.equals(method);</span><br><span class="line">         <span class="keyword">if</span> (isGet || <span class="string">&quot;HEAD&quot;</span>.equals(method)) &#123;</span><br><span class="line">            <span class="keyword">long</span> lastModified = ha.getLastModified(request, mappedHandler.getHandler());</span><br><span class="line">            <span class="keyword">if</span> (<span class="keyword">new</span> ServletWebRequest(request, response).checkNotModified(lastModified) &amp;&amp; isGet) &#123;</span><br><span class="line">               <span class="keyword">return</span>;</span><br><span class="line">            &#125;</span><br><span class="line">         &#125;</span><br><span class="line"></span><br><span class="line">         <span class="keyword">if</span> (!mappedHandler.applyPreHandle(processedRequest, response)) &#123;</span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line">         &#125;</span><br><span class="line"></span><br><span class="line">         <span class="comment">// Actually invoke the handler.</span></span><br><span class="line">         mv = ha.handle(processedRequest, response, mappedHandler.getHandler());</span><br><span class="line"></span><br><span class="line">         <span class="keyword">if</span> (asyncManager.isConcurrentHandlingStarted()) &#123;</span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line">         &#125;</span><br><span class="line"></span><br><span class="line">         applyDefaultViewName(processedRequest, mv);</span><br><span class="line">         mappedHandler.applyPostHandle(processedRequest, response, mv);</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">catch</span> (Exception ex) &#123;</span><br><span class="line">         dispatchException = ex;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">catch</span> (Throwable err) &#123;</span><br><span class="line">         <span class="comment">// As of 4.3, we&#x27;re processing Errors thrown from handler methods as well,</span></span><br><span class="line">         <span class="comment">// making them available for @ExceptionHandler methods and other scenarios.</span></span><br><span class="line">         dispatchException = <span class="keyword">new</span> NestedServletException(<span class="string">&quot;Handler dispatch failed&quot;</span>, err);</span><br><span class="line">      &#125;</span><br><span class="line">      processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException);</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="keyword">catch</span> (Exception ex) &#123;</span><br><span class="line">      triggerAfterCompletion(processedRequest, response, mappedHandler, ex);</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="keyword">catch</span> (Throwable err) &#123;</span><br><span class="line">      triggerAfterCompletion(processedRequest, response, mappedHandler,</span><br><span class="line">            <span class="keyword">new</span> NestedServletException(<span class="string">&quot;Handler processing failed&quot;</span>, err));</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="keyword">finally</span> &#123;</span><br><span class="line">      <span class="keyword">if</span> (asyncManager.isConcurrentHandlingStarted()) &#123;</span><br><span class="line">         <span class="comment">// Instead of postHandle and afterCompletion</span></span><br><span class="line">         <span class="keyword">if</span> (mappedHandler != <span class="keyword">null</span>) &#123;</span><br><span class="line">            mappedHandler.applyAfterConcurrentHandlingStarted(processedRequest, response);</span><br><span class="line">         &#125;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">else</span> &#123;</span><br><span class="line">         <span class="comment">// Clean up any resources used by a multipart request.</span></span><br><span class="line">         <span class="keyword">if</span> (multipartRequestParsed) &#123;</span><br><span class="line">            cleanupMultipart(processedRequest);</span><br><span class="line">         &#125;</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h3 id="doDispatch处理大流程图"><a href="#doDispatch处理大流程图" class="headerlink" title="doDispatch处理大流程图"></a>doDispatch处理大流程图</h3><img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_09/doDispatch处理大流程.jpg">





<h3 id="DispatcherServlet-checkMultipart"><a href="#DispatcherServlet-checkMultipart" class="headerlink" title="DispatcherServlet#checkMultipart()"></a>DispatcherServlet#checkMultipart()</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> HttpServletRequest <span class="title">checkMultipart</span><span class="params">(HttpServletRequest request)</span> <span class="keyword">throws</span> MultipartException </span>&#123;</span><br><span class="line">    <span class="comment">//使用文件上传解析器来判断是否文件上传请求</span></span><br><span class="line">   <span class="keyword">if</span> (<span class="keyword">this</span>.multipartResolver != <span class="keyword">null</span> &amp;&amp; <span class="keyword">this</span>.multipartResolver.isMultipart(request)) &#123;</span><br><span class="line"> 		<span class="comment">// ......</span></span><br><span class="line">   &#125;</span><br><span class="line">   <span class="comment">// If not returned before: return original request.</span></span><br><span class="line">   <span class="keyword">return</span> request;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_09/image-20211017205843256.png" />

<p>咱们这里目前连解析器都没有，所以就直接返回了</p>
<h3 id="StandardServletMultipartResolver-isMultipart"><a href="#StandardServletMultipartResolver-isMultipart" class="headerlink" title="StandardServletMultipartResolver#isMultipart()"></a>StandardServletMultipartResolver#isMultipart()</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">isMultipart</span><span class="params">(HttpServletRequest request)</span> </span>&#123;</span><br><span class="line">   <span class="comment">//所有文件上传请求头Content-Type都会有这个</span></span><br><span class="line">   <span class="keyword">return</span> StringUtils.startsWithIgnoreCase(request.getContentType(), <span class="string">&quot;multipart/&quot;</span>); </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h3 id="DispatcherServlet九大组件"><a href="#DispatcherServlet九大组件" class="headerlink" title="DispatcherServlet九大组件"></a>DispatcherServlet九大组件</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//DispatcherServlet中的九大组件、全是接口，我们完全可以自定义实现。Spring默认也都准备好了这些组件的实现</span></span><br><span class="line"><span class="comment">/** MultipartResolver used by this servlet. */</span> </span><br><span class="line"><span class="meta">@Nullable</span>  <span class="comment">//文件上传解析器</span></span><br><span class="line"><span class="keyword">private</span> MultipartResolver multipartResolver;</span><br><span class="line"></span><br><span class="line"><span class="comment">/** LocaleResolver used by this servlet. */</span></span><br><span class="line"><span class="meta">@Nullable</span>  <span class="comment">//国际化解析器 Locale（区域信息）</span></span><br><span class="line"><span class="keyword">private</span> LocaleResolver localeResolver;</span><br><span class="line"></span><br><span class="line"><span class="comment">/** ThemeResolver used by this servlet. */</span></span><br><span class="line"><span class="meta">@Nullable</span> <span class="comment">//主题解析器</span></span><br><span class="line"><span class="keyword">private</span> ThemeResolver themeResolver;</span><br><span class="line"></span><br><span class="line"><span class="comment">/** List of HandlerMappings used by this servlet. */</span></span><br><span class="line"><span class="meta">@Nullable</span> <span class="comment">//Handler（处理器、能处理请求的人（Controller））的映射：【保存的就是所有请求都由谁来处理的映射关系】</span></span><br><span class="line"><span class="keyword">private</span> List&lt;HandlerMapping&gt; handlerMappings;</span><br><span class="line"></span><br><span class="line"><span class="comment">/** List of HandlerAdapters used by this servlet. */</span></span><br><span class="line"><span class="meta">@Nullable</span> <span class="comment">//Handler处理器的适配器；是一个超级反射工具，帮我们解决参数呀，返回值这些，不需要我们很麻烦的写</span></span><br><span class="line"><span class="keyword">private</span> List&lt;HandlerAdapter&gt; handlerAdapters;</span><br><span class="line"></span><br><span class="line"><span class="comment">/** List of HandlerExceptionResolvers used by this servlet. */</span></span><br><span class="line"><span class="meta">@Nullable</span> <span class="comment">//Handler的异常解析器，异常处理功能</span></span><br><span class="line"><span class="keyword">private</span> List&lt;HandlerExceptionResolver&gt; handlerExceptionResolvers;</span><br><span class="line"></span><br><span class="line"><span class="comment">/** RequestToViewNameTranslator used by this servlet. */</span></span><br><span class="line"><span class="meta">@Nullable</span> <span class="comment">//把请求转成视图名（我们要跳转的页面地址）的翻译器【没啥用】</span></span><br><span class="line"><span class="keyword">private</span> RequestToViewNameTranslator viewNameTranslator;</span><br><span class="line"></span><br><span class="line"><span class="comment">/** FlashMapManager used by this servlet. */</span></span><br><span class="line"><span class="meta">@Nullable</span> <span class="comment">//闪存管理器</span></span><br><span class="line"><span class="keyword">private</span> FlashMapManager flashMapManager;</span><br><span class="line"></span><br><span class="line"><span class="comment">/** List of ViewResolvers used by this servlet. */</span></span><br><span class="line"><span class="meta">@Nullable</span> <span class="comment">//视图解析器（我们去哪些页面，怎么过去？）</span></span><br><span class="line"><span class="keyword">private</span> List&lt;ViewResolver&gt; viewResolvers;</span><br></pre></td></tr></table></figure>

<p><a target="_blank" rel="noopener" href="https://docs.spring.io/spring-framework/docs/current/reference/html/web.html#mvc-servlet-special-bean-types">官网介绍</a></p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_09/image-20211017210137817.png" />





<h2 id="九大组件利用Spring事件机制进行初始化"><a href="#九大组件利用Spring事件机制进行初始化" class="headerlink" title="九大组件利用Spring事件机制进行初始化"></a>九大组件利用Spring事件机制进行初始化</h2><p>上面的图我们看到九大组件有八个已经有值了，我们现在看下他们是何时有值的。怎么找就很简单，你就找这些属性的setXXX方法，最后我找到了这里</p>
<h3 id="DispatcherServlet-initStrategies"><a href="#DispatcherServlet-initStrategies" class="headerlink" title="DispatcherServlet#initStrategies()"></a>DispatcherServlet#initStrategies()</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">initStrategies</span><span class="params">(ApplicationContext context)</span> </span>&#123; <span class="comment">//初始化所有策略，九大组件在这里进行了初始化</span></span><br><span class="line">   initMultipartResolver(context); <span class="comment">//容器中有就用，没有就是null</span></span><br><span class="line">   initLocaleResolver(context); <span class="comment">//从容器中获取，没有用默认</span></span><br><span class="line">   initThemeResolver(context); <span class="comment">//从容器中获取，没有用默认</span></span><br><span class="line">   initHandlerMappings(context); <span class="comment">//从容器中获取，没有用默认</span></span><br><span class="line">   initHandlerAdapters(context); <span class="comment">//从容器中获取，没有用默认</span></span><br><span class="line">   initHandlerExceptionResolvers(context); <span class="comment">//从容器中获取，没有用默认</span></span><br><span class="line">   initRequestToViewNameTranslator(context); <span class="comment">//Spring没有浓重说他，//从容器中获取，没有用默认</span></span><br><span class="line">   initViewResolvers(context); <span class="comment">//从容器中获取，没有用默认</span></span><br><span class="line">   initFlashMapManager(context); <span class="comment">//从容器中获取，没有用默认</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>代码几乎都是一样的逻辑，咱们就只看一个举个例子</p>
<h3 id="DispatcherServlet-initLocaleResolver"><a href="#DispatcherServlet-initLocaleResolver" class="headerlink" title="DispatcherServlet#initLocaleResolver()"></a>DispatcherServlet#initLocaleResolver()</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">initLocaleResolver</span><span class="params">(ApplicationContext context)</span> </span>&#123;</span><br><span class="line">   <span class="keyword">try</span> &#123; <span class="comment">//容器中先来获取</span></span><br><span class="line">      <span class="keyword">this</span>.localeResolver = context.getBean(LOCALE_RESOLVER_BEAN_NAME, LocaleResolver.class);</span><br><span class="line">      <span class="keyword">if</span> (logger.isTraceEnabled()) &#123;</span><br><span class="line">         logger.trace(<span class="string">&quot;Detected &quot;</span> + <span class="keyword">this</span>.localeResolver);</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">else</span> <span class="keyword">if</span> (logger.isDebugEnabled()) &#123;</span><br><span class="line">         logger.debug(<span class="string">&quot;Detected &quot;</span> + <span class="keyword">this</span>.localeResolver.getClass().getSimpleName());</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="keyword">catch</span> (NoSuchBeanDefinitionException ex) &#123;</span><br><span class="line">      <span class="comment">// We need to use the default. 容器中没有，读取默认配置文件进行加载</span></span><br><span class="line">      <span class="keyword">this</span>.localeResolver = getDefaultStrategy(context, LocaleResolver.class); <span class="comment">//获取默认策略</span></span><br><span class="line">      <span class="keyword">if</span> (logger.isTraceEnabled()) &#123;</span><br><span class="line">         logger.trace(<span class="string">&quot;No LocaleResolver &#x27;&quot;</span> + LOCALE_RESOLVER_BEAN_NAME +</span><br><span class="line">               <span class="string">&quot;&#x27;: using default [&quot;</span> + <span class="keyword">this</span>.localeResolver.getClass().getSimpleName() + <span class="string">&quot;]&quot;</span>);</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>只要不满意九大组件的任何一个，自己可以实现指定的接口，这样就会放在容器中，SpringMVC</p>
<h3 id="Debug调用栈-1"><a href="#Debug调用栈-1" class="headerlink" title="Debug调用栈"></a>Debug调用栈</h3><img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_09/image-20211018162558076.png" />



<ol>
<li>Tomcat启动</li>
<li>触发DispatcherServlet的初始化</li>
<li>DispatcherServlet初始化全部结束，容器会发送Spring的相关事件.</li>
<li>感知到容器准备好了的事件–初始化九大组件(底层是SourceFilteringListener, 把事件回调到DispatcherServlet的onRefresh方法)</li>
</ol>
<h3 id="DispatcherServlet-onRefresh-接收到事件开始准备初始化九大组件"><a href="#DispatcherServlet-onRefresh-接收到事件开始准备初始化九大组件" class="headerlink" title="DispatcherServlet#onRefresh()接收到事件开始准备初始化九大组件"></a>DispatcherServlet#onRefresh()接收到事件开始准备初始化九大组件</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">onRefresh</span><span class="params">(ApplicationContext context)</span> </span>&#123;</span><br><span class="line">   initStrategies(context); <span class="comment">//初始化九大组件</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h3 id="DispatcherServlet-getDefaultStrategy-获取默认初始化策略"><a href="#DispatcherServlet-getDefaultStrategy-获取默认初始化策略" class="headerlink" title="DispatcherServlet#getDefaultStrategy() 获取默认初始化策略"></a>DispatcherServlet#getDefaultStrategy() 获取默认初始化策略</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line">   <span class="keyword">protected</span> &lt;T&gt; <span class="function">T <span class="title">getDefaultStrategy</span><span class="params">(ApplicationContext context, Class&lt;T&gt; strategyInterface)</span> </span>&#123;</span><br><span class="line">      List&lt;T&gt; strategies = getDefaultStrategies(context, strategyInterface);</span><br><span class="line">      <span class="keyword">if</span> (strategies.size() != <span class="number">1</span>) &#123;</span><br><span class="line">         <span class="keyword">throw</span> <span class="keyword">new</span> BeanInitializationException(</span><br><span class="line">               <span class="string">&quot;DispatcherServlet needs exactly 1 strategy for interface [&quot;</span> + strategyInterface.getName() + <span class="string">&quot;]&quot;</span>);</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">return</span> strategies.get(<span class="number">0</span>);</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">protected</span> &lt;T&gt; <span class="function">List&lt;T&gt; <span class="title">getDefaultStrategies</span><span class="params">(ApplicationContext context, Class&lt;T&gt; strategyInterface)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">if</span> (defaultStrategies == <span class="keyword">null</span>) &#123;</span><br><span class="line">		<span class="keyword">try</span> &#123;</span><br><span class="line">			<span class="comment">// Load default strategy implementations from properties file.</span></span><br><span class="line">			<span class="comment">// This is currently strictly internal and not meant to be customized</span></span><br><span class="line">			<span class="comment">// by application developers. 去DispatcherServlet所在的类路径下找一个 DispatcherServlet.properties 资源</span></span><br><span class="line">			ClassPathResource resource = <span class="keyword">new</span> ClassPathResource(DEFAULT_STRATEGIES_PATH, DispatcherServlet.class);</span><br><span class="line">			defaultStrategies = PropertiesLoaderUtils.loadProperties(resource); <span class="comment">//读取properties文件</span></span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">catch</span> (IOException ex) &#123;</span><br><span class="line">			<span class="keyword">throw</span> <span class="keyword">new</span> IllegalStateException(<span class="string">&quot;Could not load &#x27;&quot;</span> + DEFAULT_STRATEGIES_PATH + <span class="string">&quot;&#x27;: &quot;</span> + ex.getMessage());</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">// ......</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> String DEFAULT_STRATEGIES_PATH = <span class="string">&quot;DispatcherServlet.properties&quot;</span>;</span><br></pre></td></tr></table></figure>



<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_09/image-20211018164740715.png" />



<h4 id="DispatcherServlet-properties"><a href="#DispatcherServlet-properties" class="headerlink" title="DispatcherServlet.properties"></a>DispatcherServlet.properties</h4><p>下面这些就是九大组件默认组件</p>
<figure class="highlight properties"><table><tr><td class="code"><pre><span class="line"><span class="comment"># Default implementation classes for DispatcherServlet&#x27;s strategy interfaces.</span></span><br><span class="line"><span class="comment"># Used as fallback when no matching beans are found in the DispatcherServlet context.</span></span><br><span class="line"><span class="comment"># Not meant to be customized by application developers.</span></span><br><span class="line"></span><br><span class="line"><span class="meta">org.springframework.web.servlet.LocaleResolver</span>=<span class="string">org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver</span></span><br><span class="line"></span><br><span class="line"><span class="meta">org.springframework.web.servlet.ThemeResolver</span>=<span class="string">org.springframework.web.servlet.theme.FixedThemeResolver</span></span><br><span class="line"></span><br><span class="line"><span class="meta">org.springframework.web.servlet.HandlerMapping</span>=<span class="string">org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping,\</span></span><br><span class="line">   org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping,\</span><br><span class="line">   <span class="attr">org.springframework.web.servlet.function.support.RouterFunctionMapping</span></span><br><span class="line"></span><br><span class="line"><span class="meta">org.springframework.web.servlet.HandlerAdapter</span>=<span class="string">org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter,\</span></span><br><span class="line">   org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter,\</span><br><span class="line">   org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter,\</span><br><span class="line">   <span class="attr">org.springframework.web.servlet.function.support.HandlerFunctionAdapter</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="meta">org.springframework.web.servlet.HandlerExceptionResolver</span>=<span class="string">org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver,\</span></span><br><span class="line">   org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver,\</span><br><span class="line">   <span class="attr">org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver</span></span><br><span class="line"></span><br><span class="line"><span class="meta">org.springframework.web.servlet.RequestToViewNameTranslator</span>=<span class="string">org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator</span></span><br><span class="line"></span><br><span class="line"><span class="meta">org.springframework.web.servlet.ViewResolver</span>=<span class="string">org.springframework.web.servlet.view.InternalResourceViewResolver</span></span><br><span class="line"></span><br><span class="line"><span class="meta">org.springframework.web.servlet.FlashMapManager</span>=<span class="string">org.springframework.web.servlet.support.SessionFlashMapManager</span></span><br></pre></td></tr></table></figure>



<h2 id="HandlerMapping处理URL和Controller的映射关系"><a href="#HandlerMapping处理URL和Controller的映射关系" class="headerlink" title="HandlerMapping处理URL和Controller的映射关系"></a>HandlerMapping处理URL和Controller的映射关系</h2><h3 id="DispatcherServlet-doDispatch-请求派发-1"><a href="#DispatcherServlet-doDispatch-请求派发-1" class="headerlink" title="DispatcherServlet#doDispatch()请求派发"></a>DispatcherServlet#doDispatch()请求派发</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//SpringMVC处理请求的核心流程</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">doDispatch</span><span class="params">(HttpServletRequest request, HttpServletResponse response)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">   HttpServletRequest processedRequest = request;</span><br><span class="line">   HandlerExecutionChain mappedHandler = <span class="keyword">null</span>; <span class="comment">//handler（目标方法）的执行链</span></span><br><span class="line">   <span class="keyword">boolean</span> multipartRequestParsed = <span class="keyword">false</span>; <span class="comment">//文件上传标志</span></span><br><span class="line">   <span class="comment">//对异步请求的支持（Servlet3.0以后才有的，Webflux）</span></span><br><span class="line">   WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);</span><br><span class="line"></span><br><span class="line">   <span class="keyword">try</span> &#123;</span><br><span class="line">      ModelAndView mv = <span class="keyword">null</span>;</span><br><span class="line">      Exception dispatchException = <span class="keyword">null</span>;</span><br><span class="line"></span><br><span class="line">      <span class="keyword">try</span> &#123;</span><br><span class="line">         processedRequest = checkMultipart(request); <span class="comment">//检查当前是否文件上传请求</span></span><br><span class="line">         multipartRequestParsed = (processedRequest != request);</span><br><span class="line"></span><br><span class="line">         <span class="comment">//构造出了【目标方法+拦截器整个链路】决定使用哪个Handler处理当前请求 Determine handler for the current request.</span></span><br><span class="line">         mappedHandler = getHandler(processedRequest);</span><br><span class="line">         <span class="keyword">if</span> (mappedHandler == <span class="keyword">null</span>) &#123;  <span class="comment">//如果找不到人处理，就send 404</span></span><br><span class="line">            noHandlerFound(processedRequest, response);</span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line">         &#125;</span><br><span class="line"></span><br><span class="line">         <span class="comment">//适配器怎么找的、 Determine handler adapter for the current request.</span></span><br><span class="line">         HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());</span><br><span class="line"></span><br><span class="line">         <span class="comment">// Process last-modified header, if supported by the handler.</span></span><br><span class="line">         String method = request.getMethod();</span><br><span class="line">         <span class="keyword">boolean</span> isGet = <span class="string">&quot;GET&quot;</span>.equals(method);</span><br><span class="line">         <span class="keyword">if</span> (isGet || <span class="string">&quot;HEAD&quot;</span>.equals(method)) &#123;</span><br><span class="line">            <span class="keyword">long</span> lastModified = ha.getLastModified(request, mappedHandler.getHandler());</span><br><span class="line">            <span class="keyword">if</span> (<span class="keyword">new</span> ServletWebRequest(request, response).checkNotModified(lastModified) &amp;&amp; isGet) &#123;</span><br><span class="line">               <span class="keyword">return</span>;</span><br><span class="line">            &#125;</span><br><span class="line">         &#125;</span><br><span class="line"></span><br><span class="line">         <span class="keyword">if</span> (!mappedHandler.applyPreHandle(processedRequest, response)) &#123;</span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line">         &#125;</span><br><span class="line"></span><br><span class="line">         <span class="comment">// Actually invoke the handler.</span></span><br><span class="line">         mv = ha.handle(processedRequest, response, mappedHandler.getHandler());</span><br><span class="line"></span><br><span class="line">         <span class="keyword">if</span> (asyncManager.isConcurrentHandlingStarted()) &#123;</span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line">         &#125;</span><br><span class="line"></span><br><span class="line">         applyDefaultViewName(processedRequest, mv);</span><br><span class="line">         mappedHandler.applyPostHandle(processedRequest, response, mv);</span><br><span class="line">      &#125;</span><br><span class="line">      processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException);</span><br><span class="line">   &#125;</span><br><span class="line">    </span><br><span class="line">   <span class="comment">// ......</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>





<h3 id="DispatcherServlet-getHandler-根据请求拿Controller"><a href="#DispatcherServlet-getHandler-根据请求拿Controller" class="headerlink" title="DispatcherServlet#getHandler()根据请求拿Controller"></a>DispatcherServlet#getHandler()根据请求拿Controller</h3><img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_09/image-20211018165759982.png" />



<p>这里会有三个默认的HandlerMapping，就是在DispatcherServlet.properties写的那三个，在之前说九大组件初始化的时候如果我们自己没有写，就获取默认的</p>
<ol>
<li>BeanNameUrlHandlerMapping：bean的名字作为URL路径，进行映射</li>
<li>RequestMappingHandlerMapping：@RequestMapping注解作为URL地址进行映射<ol>
<li>默认用它，而且它里面保存了所有请求映射信息</li>
</ol>
</li>
<li>RouterFunctionMapping: 支持函数式处理以及WebFlux相关功能，未来可能这个用的多</li>
</ol>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_09/image-20211018170430551.png"/>

<p>BeanNameUrlHandlerMapping里找不到映射关系，就直接下一个循环了。咱们主要看RequestMappingHandlerMapping怎么处理的</p>
<h2 id="RequestMappingHandlerMapping处理流程"><a href="#RequestMappingHandlerMapping处理流程" class="headerlink" title="RequestMappingHandlerMapping处理流程"></a>RequestMappingHandlerMapping处理流程</h2><img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_09/image-20211018170624402.png" />



<p>RequestMappingHandlerMapping的父类有一个MappingRegistry属性保存了请求路径 ==&gt; 请求Controller+方法的映射</p>
<p>F7进入<code>mapping.getHandler(request)</code></p>
<h3 id="AbstractHandlerMapping-getHandler-开始根据请求URL查哪个Controler能处理"><a href="#AbstractHandlerMapping-getHandler-开始根据请求URL查哪个Controler能处理" class="headerlink" title="AbstractHandlerMapping#getHandler()开始根据请求URL查哪个Controler能处理"></a>AbstractHandlerMapping#getHandler()开始根据请求URL查哪个Controler能处理</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">final</span> HandlerExecutionChain <span class="title">getHandler</span><span class="params">(HttpServletRequest request)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">   Object handler = getHandlerInternal(request); <span class="comment">//HandlerMapping的registry中找映射，返回HandlerMethod，真正执行当前请求的方法</span></span><br><span class="line">   <span class="keyword">if</span> (handler == <span class="keyword">null</span>) &#123;</span><br><span class="line">      handler = getDefaultHandler();</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="keyword">if</span> (handler == <span class="keyword">null</span>) &#123;</span><br><span class="line">      <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="comment">// Bean name or resolved handler?</span></span><br><span class="line">   <span class="keyword">if</span> (handler <span class="keyword">instanceof</span> String) &#123;</span><br><span class="line">      String handlerName = (String) handler;</span><br><span class="line">      handler = obtainApplicationContext().getBean(handlerName);</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="comment">// Ensure presence of cached lookupPath for interceptors and others</span></span><br><span class="line">   <span class="keyword">if</span> (!ServletRequestPathUtils.hasCachedPath(request)) &#123;</span><br><span class="line">      initLookupPath(request);</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="comment">//找到前面的目标方法以后，还要构造一个处理器链;</span></span><br><span class="line">   HandlerExecutionChain executionChain = getHandlerExecutionChain(handler, request);</span><br><span class="line"></span><br><span class="line">   <span class="keyword">if</span> (logger.isTraceEnabled()) &#123;</span><br><span class="line">      logger.trace(<span class="string">&quot;Mapped to &quot;</span> + handler);</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="keyword">else</span> <span class="keyword">if</span> (logger.isDebugEnabled() &amp;&amp; !request.getDispatcherType().equals(DispatcherType.ASYNC)) &#123;</span><br><span class="line">      logger.debug(<span class="string">&quot;Mapped to &quot;</span> + executionChain.getHandler());</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="keyword">if</span> (hasCorsConfigurationSource(handler) || CorsUtils.isPreFlightRequest(request)) &#123;</span><br><span class="line">      CorsConfiguration config = getCorsConfiguration(handler, request);</span><br><span class="line">      <span class="keyword">if</span> (getCorsConfigurationSource() != <span class="keyword">null</span>) &#123;</span><br><span class="line">         CorsConfiguration globalConfig = getCorsConfigurationSource().getCorsConfiguration(request);</span><br><span class="line">         config = (globalConfig != <span class="keyword">null</span> ? globalConfig.combine(config) : config);</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">if</span> (config != <span class="keyword">null</span>) &#123;</span><br><span class="line">         config.validateAllowCredentials();</span><br><span class="line">      &#125;</span><br><span class="line">      executionChain = getCorsHandlerExecutionChain(request, executionChain, config);</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="keyword">return</span> executionChain;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_09/image-20211018172011789.png"  />

<p>F7进入<code>getHandlerInternal(request)</code></p>
<h3 id="RequestMappingInfoHandlerMapping-getHandlerInternal"><a href="#RequestMappingInfoHandlerMapping-getHandlerInternal" class="headerlink" title="RequestMappingInfoHandlerMapping#getHandlerInternal()"></a>RequestMappingInfoHandlerMapping#getHandlerInternal()</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> HandlerMethod <span class="title">getHandlerInternal</span><span class="params">(HttpServletRequest request)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">   request.removeAttribute(PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE);</span><br><span class="line">   <span class="keyword">try</span> &#123;</span><br><span class="line">      <span class="keyword">return</span> <span class="keyword">super</span>.getHandlerInternal(request);</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="keyword">finally</span> &#123;</span><br><span class="line">      ProducesRequestCondition.clearMediaTypesAttribute(request);</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>继续F7进<code>super.getHandlerInternal(request)</code></p>
<h3 id="AbstractHandlerMethodMapping-getHandlerInternal"><a href="#AbstractHandlerMethodMapping-getHandlerInternal" class="headerlink" title="AbstractHandlerMethodMapping#getHandlerInternal()"></a>AbstractHandlerMethodMapping#getHandlerInternal()</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> HandlerMethod <span class="title">getHandlerInternal</span><span class="params">(HttpServletRequest request)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">   String lookupPath = initLookupPath(request);</span><br><span class="line">   <span class="keyword">this</span>.mappingRegistry.acquireReadLock();</span><br><span class="line">   <span class="keyword">try</span> &#123;</span><br><span class="line">      HandlerMethod handlerMethod = lookupHandlerMethod(lookupPath, request); <span class="comment">//寻找当前请求谁能处理</span></span><br><span class="line">      <span class="keyword">return</span> (handlerMethod != <span class="keyword">null</span> ? handlerMethod.createWithResolvedBean() : <span class="keyword">null</span>);</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="keyword">finally</span> &#123;</span><br><span class="line">      <span class="keyword">this</span>.mappingRegistry.releaseReadLock();</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_09/image-20211018172342398.png"  />

<p>F7进入<code>lookupHandlerMethod(lookupPath, request)</code></p>
<h3 id="AbstractHandlerMethodMapping-lookupHandlerMethod-真正根据URL查Controller"><a href="#AbstractHandlerMethodMapping-lookupHandlerMethod-真正根据URL查Controller" class="headerlink" title="AbstractHandlerMethodMapping#lookupHandlerMethod()真正根据URL查Controller"></a>AbstractHandlerMethodMapping#lookupHandlerMethod()真正根据URL查Controller</h3><img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_09/image-20211018173123281.png"/>



<p>可以看到还是从mappingRegistry里获取。我们后面再看mappingRegistry是什么时候被放入东西的，这里我们接着返回</p>
<h3 id="返回到AbstractHandlerMethodMapping-getHandlerInternal"><a href="#返回到AbstractHandlerMethodMapping-getHandlerInternal" class="headerlink" title="返回到AbstractHandlerMethodMapping#getHandlerInternal()"></a>返回到AbstractHandlerMethodMapping#getHandlerInternal()</h3><img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_09/image-20211018185954647.png"/>

<p>这个时候是已经找到了由哪个处理器处理，接着返回</p>
<h3 id="返回到AbstractHandlerMapping-getHandler"><a href="#返回到AbstractHandlerMapping-getHandler" class="headerlink" title="返回到AbstractHandlerMapping#getHandler()"></a>返回到AbstractHandlerMapping#getHandler()</h3><p>返回到这一步，准备执行<code>getHandlerExecutionChain(handler, request)</code></p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_09/image-20211018190338925.png"  />



<h3 id="AbstractHandlerMapping-getHandlerExecutionChain-开始构造处理器链"><a href="#AbstractHandlerMapping-getHandlerExecutionChain-开始构造处理器链" class="headerlink" title="AbstractHandlerMapping#getHandlerExecutionChain()开始构造处理器链"></a>AbstractHandlerMapping#getHandlerExecutionChain()开始构造处理器链</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> HandlerExecutionChain <span class="title">getHandlerExecutionChain</span><span class="params">(Object handler, HttpServletRequest request)</span> </span>&#123;</span><br><span class="line">   HandlerExecutionChain chain = (handler <span class="keyword">instanceof</span> HandlerExecutionChain ?</span><br><span class="line">         (HandlerExecutionChain) handler : <span class="keyword">new</span> HandlerExecutionChain(handler));</span><br><span class="line">   <span class="comment">//把系统中所有的拦截器拿过来</span></span><br><span class="line">   <span class="keyword">for</span> (HandlerInterceptor interceptor : <span class="keyword">this</span>.adaptedInterceptors) &#123;</span><br><span class="line">      <span class="keyword">if</span> (interceptor <span class="keyword">instanceof</span> MappedInterceptor) &#123;</span><br><span class="line">         MappedInterceptor mappedInterceptor = (MappedInterceptor) interceptor;</span><br><span class="line">         <span class="keyword">if</span> (mappedInterceptor.matches(request)) &#123;</span><br><span class="line">            chain.addInterceptor(mappedInterceptor.getInterceptor());</span><br><span class="line">         &#125;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">else</span> &#123;</span><br><span class="line">         chain.addInterceptor(interceptor); <span class="comment">//所有拦截器加进去</span></span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="keyword">return</span> chain;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_09/image-20211018190711035.png"  />

<ul>
<li>咱们没写拦截器，就没有。</li>
<li>继续往回返</li>
</ul>
<h3 id="返回到DispatcherServlet-getHandler"><a href="#返回到DispatcherServlet-getHandler" class="headerlink" title="返回到DispatcherServlet#getHandler()"></a>返回到DispatcherServlet#getHandler()</h3><img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_09/image-20211018190924151.png"  />

<p>这里就是责任链模式，有能处理的handler就直接返回</p>
<h3 id="返回到DispatcherServlet-doDispatch"><a href="#返回到DispatcherServlet-doDispatch" class="headerlink" title="返回到DispatcherServlet#doDispatch()"></a>返回到DispatcherServlet#doDispatch()</h3><img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_09/image-20211018191048955.png" />

<p>自此RequestMappingHandlerMapping处理结束</p>
<h2 id="RequestMappingHandlerMapping如何保存映射关系"><a href="#RequestMappingHandlerMapping如何保存映射关系" class="headerlink" title="RequestMappingHandlerMapping如何保存映射关系"></a>RequestMappingHandlerMapping如何保存映射关系</h2><p>上面我们看到了实际上是从MappingRegistry里拿到URL–&gt;XXXController的映射关系的，那么下面就来演讲MappingRegistry是何时保存的这映射关系，又是怎样保存的</p>
<h3 id="AbstractHandlerMethodMapping-registerMapping"><a href="#AbstractHandlerMethodMapping-registerMapping" class="headerlink" title="AbstractHandlerMethodMapping#registerMapping()"></a>AbstractHandlerMethodMapping#registerMapping()</h3><p>我们这里还是靠猜测，猜它调用哪个方法。找到了如下方法，给第一行打断点，重启。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//分析所有的Controller；里面的每一个@RequestMapping 注解才能知道这个事情</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">registerMapping</span><span class="params">(T mapping, Object handler, Method method)</span> </span>&#123; <span class="comment">//哪个请求由哪个方法处理会通过这个进行注册</span></span><br><span class="line">   <span class="keyword">if</span> (logger.isTraceEnabled()) &#123;</span><br><span class="line">      logger.trace(<span class="string">&quot;Register \&quot;&quot;</span> + mapping + <span class="string">&quot;\&quot; to &quot;</span> + method.toGenericString());</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="keyword">this</span>.mappingRegistry.register(mapping, handler, method);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>重启的时候没有发现没跑到这里，然后我就看了下这个MappingRegistry，发现它是个AbstractHandlerMethodMapping的内部类</p>
<h4 id="MappingRegistry-URL-gt-XXXController的映射中心"><a href="#MappingRegistry-URL-gt-XXXController的映射中心" class="headerlink" title="MappingRegistry(URL=&gt;XXXController的映射中心)"></a>MappingRegistry(URL=&gt;XXXController的映射中心)</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MappingRegistry</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">   <span class="keyword">private</span> <span class="keyword">final</span> Map&lt;T, MappingRegistration&lt;T&gt;&gt; registry = <span class="keyword">new</span> HashMap&lt;&gt;();</span><br><span class="line"></span><br><span class="line">   <span class="keyword">private</span> <span class="keyword">final</span> MultiValueMap&lt;String, T&gt; pathLookup = <span class="keyword">new</span> LinkedMultiValueMap&lt;&gt;();</span><br><span class="line"></span><br><span class="line">   <span class="keyword">private</span> <span class="keyword">final</span> Map&lt;String, List&lt;HandlerMethod&gt;&gt; nameLookup = <span class="keyword">new</span> ConcurrentHashMap&lt;&gt;();</span><br><span class="line"></span><br><span class="line">   <span class="keyword">private</span> <span class="keyword">final</span> Map&lt;HandlerMethod, CorsConfiguration&gt; corsLookup = <span class="keyword">new</span> ConcurrentHashMap&lt;&gt;();</span><br><span class="line"></span><br><span class="line">   <span class="keyword">private</span> <span class="keyword">final</span> ReentrantReadWriteLock readWriteLock = <span class="keyword">new</span> ReentrantReadWriteLock();</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">register</span><span class="params">(T mapping, Object handler, Method method)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.readWriteLock.writeLock().lock();</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            HandlerMethod handlerMethod = createHandlerMethod(handler, method);</span><br><span class="line">            validateMethodMapping(handlerMethod, mapping);</span><br><span class="line"></span><br><span class="line">            Set&lt;String&gt; directPaths = AbstractHandlerMethodMapping.<span class="keyword">this</span>.getDirectPaths(mapping);</span><br><span class="line">            <span class="keyword">for</span> (String path : directPaths) &#123;</span><br><span class="line">                <span class="keyword">this</span>.pathLookup.add(path, mapping);</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            String name = <span class="keyword">null</span>;</span><br><span class="line">            <span class="keyword">if</span> (getNamingStrategy() != <span class="keyword">null</span>) &#123;</span><br><span class="line">                name = getNamingStrategy().getName(handlerMethod, mapping);</span><br><span class="line">                addMappingName(name, handlerMethod);</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            CorsConfiguration corsConfig = initCorsConfiguration(handler, method, mapping);</span><br><span class="line">            <span class="keyword">if</span> (corsConfig != <span class="keyword">null</span>) &#123;</span><br><span class="line">                corsConfig.validateAllowCredentials();</span><br><span class="line">                <span class="keyword">this</span>.corsLookup.put(handlerMethod, corsConfig);</span><br><span class="line">            &#125;</span><br><span class="line">		   <span class="comment">// 在这里put的</span></span><br><span class="line">            <span class="keyword">this</span>.registry.put(mapping,</span><br><span class="line">                              <span class="keyword">new</span> MappingRegistration&lt;&gt;(mapping, handlerMethod, directPaths, name, corsConfig != <span class="keyword">null</span>));</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">finally</span> &#123;</span><br><span class="line">            <span class="keyword">this</span>.readWriteLock.writeLock().unlock();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>我发现上面有一个registry是个Map类型，很容易想到这应该就是保存映射的，然后我就在它的put方法那里打断点，只找到了这一个put。重启应用</p>
<h3 id="Debug调用栈-2"><a href="#Debug调用栈-2" class="headerlink" title="Debug调用栈"></a>Debug调用栈</h3><img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_09/image-20211018174537002.png"  />

<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_09/image-20211018174827232.png" />

<p>意料之中，启动应用的时候从init初始化那里调用过来了</p>
<h4 id="流程概述"><a href="#流程概述" class="headerlink" title="流程概述"></a>流程概述</h4><ol>
<li><code>DispatcherServlet#onRefresh()</code>开始初始化九大组件，就会开始初始化HandlerMapping</li>
<li>首先是创建<code>DispatcherServlet.properties</code>里指定的三个HandlerMapping实现类的对象。还是用createBean来创建HandlerMapping的</li>
<li>其中RequestMappingHandlerMapping创建完对象后，因为它实现了InitializingBean，所以会调用RequestMappingHandlerMapping#afterPropertiesSet()</li>
<li>接着就是拿到Web子容器的所有组件，for循环处理。看是不是有@Controller注解或者@RequestMapping注解</li>
<li>最后把分析到的RequestMapping信息放到HandlerMapping的registry中</li>
</ol>
<h3 id="RequestMappingHandlerMapping-afterPropertiesSet"><a href="#RequestMappingHandlerMapping-afterPropertiesSet" class="headerlink" title="RequestMappingHandlerMapping#afterPropertiesSet()"></a>RequestMappingHandlerMapping#afterPropertiesSet()</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">afterPropertiesSet</span><span class="params">()</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">   <span class="keyword">this</span>.config = <span class="keyword">new</span> RequestMappingInfo.BuilderConfiguration();</span><br><span class="line">   <span class="keyword">this</span>.config.setTrailingSlashMatch(useTrailingSlashMatch());</span><br><span class="line">   <span class="keyword">this</span>.config.setContentNegotiationManager(getContentNegotiationManager());</span><br><span class="line"></span><br><span class="line">   <span class="keyword">if</span> (getPatternParser() != <span class="keyword">null</span>) &#123;</span><br><span class="line">      <span class="keyword">this</span>.config.setPatternParser(getPatternParser());</span><br><span class="line">      Assert.isTrue(!<span class="keyword">this</span>.useSuffixPatternMatch &amp;&amp; !<span class="keyword">this</span>.useRegisteredSuffixPatternMatch,</span><br><span class="line">            <span class="string">&quot;Suffix pattern matching not supported with PathPatternParser.&quot;</span>);</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="keyword">else</span> &#123;</span><br><span class="line">      <span class="keyword">this</span>.config.setSuffixPatternMatch(useSuffixPatternMatch());</span><br><span class="line">      <span class="keyword">this</span>.config.setRegisteredSuffixPatternMatch(useRegisteredSuffixPatternMatch());</span><br><span class="line">      <span class="keyword">this</span>.config.setPathMatcher(getPathMatcher());</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="keyword">super</span>.afterPropertiesSet();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h3 id="AbstractHandlerMethodMapping-afterPropertiesSet"><a href="#AbstractHandlerMethodMapping-afterPropertiesSet" class="headerlink" title="AbstractHandlerMethodMapping#afterPropertiesSet()"></a>AbstractHandlerMethodMapping#afterPropertiesSet()</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">afterPropertiesSet</span><span class="params">()</span> </span>&#123;</span><br><span class="line">   initHandlerMethods(); <span class="comment">//初始化HandlerMethods。</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h3 id="AbstractHandlerMethodMapping-initHandlerMethods-初始化HandlerMethods"><a href="#AbstractHandlerMethodMapping-initHandlerMethods-初始化HandlerMethods" class="headerlink" title="AbstractHandlerMethodMapping#initHandlerMethods()初始化HandlerMethods"></a>AbstractHandlerMethodMapping#initHandlerMethods()初始化HandlerMethods</h3><img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_09/image-20211018175412239.png" />



<p>可以看到这里只拿了Web子容器的所有组件进行for循环</p>
<h3 id="AbstractHandlerMethodMapping-processCandidateBean"><a href="#AbstractHandlerMethodMapping-processCandidateBean" class="headerlink" title="AbstractHandlerMethodMapping#processCandidateBean()"></a>AbstractHandlerMethodMapping#processCandidateBean()</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">processCandidateBean</span><span class="params">(String beanName)</span> </span>&#123;</span><br><span class="line">   Class&lt;?&gt; beanType = <span class="keyword">null</span>;</span><br><span class="line">   <span class="keyword">try</span> &#123;</span><br><span class="line">      beanType = obtainApplicationContext().getType(beanName);</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="keyword">catch</span> (Throwable ex) &#123;</span><br><span class="line">      <span class="comment">// An unresolvable bean type, probably from a lazy bean - let&#x27;s ignore it.</span></span><br><span class="line">      <span class="keyword">if</span> (logger.isTraceEnabled()) &#123;</span><br><span class="line">         logger.trace(<span class="string">&quot;Could not resolve type for bean &#x27;&quot;</span> + beanName + <span class="string">&quot;&#x27;&quot;</span>, ex);</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="keyword">if</span> (beanType != <span class="keyword">null</span> &amp;&amp; isHandler(beanType)) &#123;</span><br><span class="line">      detectHandlerMethods(beanName); <span class="comment">//分析当前bean的HandlerMethods</span></span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h3 id="RequestMappingHandlerMapping-isHandler-判断当前bean是不是Handler"><a href="#RequestMappingHandlerMapping-isHandler-判断当前bean是不是Handler" class="headerlink" title="RequestMappingHandlerMapping#isHandler()判断当前bean是不是Handler"></a>RequestMappingHandlerMapping#isHandler()判断当前bean是不是Handler</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">boolean</span> <span class="title">isHandler</span><span class="params">(Class&lt;?&gt; beanType)</span> </span>&#123;</span><br><span class="line">   <span class="keyword">return</span> (AnnotatedElementUtils.hasAnnotation(beanType, Controller.class) ||</span><br><span class="line">         AnnotatedElementUtils.hasAnnotation(beanType, RequestMapping.class));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ol>
<li>这里首先会过滤Bean，只有你Bean也就是类上标注了@Controller注解或者@RequestMapping注解，才会给这个类走下面的流程</li>
<li>那这个是什么意思呢？</li>
<li>平常我们写XXXController就是写一个@Controller注解就完事了【注意@RestController值是@Controller的复合注解，包含了@Controller】</li>
<li>实际上我们可以不写@Controller注解，直接@Component+@RequestMapping也是一样的效果</li>
</ol>
<h3 id="AbstractHandlerMethodMapping-detectHandlerMethods-探查容器里满足条件的方法"><a href="#AbstractHandlerMethodMapping-detectHandlerMethods-探查容器里满足条件的方法" class="headerlink" title="AbstractHandlerMethodMapping#detectHandlerMethods()探查容器里满足条件的方法"></a>AbstractHandlerMethodMapping#detectHandlerMethods()探查容器里满足条件的方法</h3><ol>
<li>然后那个detectHandlerMethods就是探查容器里满足条件的方法</li>
<li>下面看下怎么探索的</li>
</ol>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">detectHandlerMethods</span><span class="params">(Object handler)</span> </span>&#123;</span><br><span class="line">   Class&lt;?&gt; handlerType = (handler <span class="keyword">instanceof</span> String ?</span><br><span class="line">         obtainApplicationContext().getType((String) handler) : handler.getClass());</span><br><span class="line"></span><br><span class="line">   <span class="keyword">if</span> (handlerType != <span class="keyword">null</span>) &#123;</span><br><span class="line">      Class&lt;?&gt; userType = ClassUtils.getUserClass(handlerType);</span><br><span class="line">      Map&lt;Method, T&gt; methods = MethodIntrospector.selectMethods(userType,</span><br><span class="line">            (MethodIntrospector.MetadataLookup&lt;T&gt;) method -&gt; &#123;</span><br><span class="line">               <span class="keyword">try</span> &#123;</span><br><span class="line">                  <span class="keyword">return</span> getMappingForMethod(method, userType); <span class="comment">//探索当前类里面所有满足的方法，所有标注了 RequestMapping</span></span><br><span class="line">               &#125;</span><br><span class="line">               <span class="keyword">catch</span> (Throwable ex) &#123;</span><br><span class="line">                  <span class="keyword">throw</span> <span class="keyword">new</span> IllegalStateException(<span class="string">&quot;Invalid mapping on handler class [&quot;</span> +</span><br><span class="line">                        userType.getName() + <span class="string">&quot;]: &quot;</span> + method, ex);</span><br><span class="line">               &#125;</span><br><span class="line">            &#125;);</span><br><span class="line">      <span class="keyword">if</span> (logger.isTraceEnabled()) &#123;</span><br><span class="line">         logger.trace(formatMappings(userType, methods));</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">else</span> <span class="keyword">if</span> (mappingsLogger.isDebugEnabled()) &#123;</span><br><span class="line">         mappingsLogger.debug(formatMappings(userType, methods));</span><br><span class="line">      &#125;</span><br><span class="line">      methods.forEach((method, mapping) -&gt; &#123;</span><br><span class="line">         Method invocableMethod = AopUtils.selectInvocableMethod(method, userType);</span><br><span class="line">         registerHandlerMethod(handler, invocableMethod, mapping);</span><br><span class="line">      &#125;);</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>





<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.6/spring-sourcecode-v1/chapter_09/image-20211018183141571.png" />



<h3 id="RequestMappingHandlerMapping-getMappingForMethod"><a href="#RequestMappingHandlerMapping-getMappingForMethod" class="headerlink" title="RequestMappingHandlerMapping#getMappingForMethod()"></a>RequestMappingHandlerMapping#getMappingForMethod()</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> RequestMappingInfo <span class="title">getMappingForMethod</span><span class="params">(Method method, Class&lt;?&gt; handlerType)</span> </span>&#123;</span><br><span class="line">   RequestMappingInfo info = createRequestMappingInfo(method); <span class="comment">//为每一个方法尝试创建 RequestMappingInfo</span></span><br><span class="line">   <span class="keyword">if</span> (info != <span class="keyword">null</span>) &#123;</span><br><span class="line">      RequestMappingInfo typeInfo = createRequestMappingInfo(handlerType);</span><br><span class="line">      <span class="keyword">if</span> (typeInfo != <span class="keyword">null</span>) &#123;</span><br><span class="line">         info = typeInfo.combine(info);</span><br><span class="line">      &#125;</span><br><span class="line">      String prefix = getPathPrefix(handlerType);</span><br><span class="line">      <span class="keyword">if</span> (prefix != <span class="keyword">null</span>) &#123;</span><br><span class="line">         info = RequestMappingInfo.paths(prefix).options(<span class="keyword">this</span>.config).build().combine(info);</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="keyword">return</span> info;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="RequestMappingHandlerMapping-createRequestMappingInfo-AnnotatedElement"><a href="#RequestMappingHandlerMapping-createRequestMappingInfo-AnnotatedElement" class="headerlink" title="RequestMappingHandlerMapping#createRequestMappingInfo(AnnotatedElement )"></a>RequestMappingHandlerMapping#createRequestMappingInfo(AnnotatedElement )</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Nullable</span>  </span><br><span class="line"><span class="function"><span class="keyword">private</span> RequestMappingInfo <span class="title">createRequestMappingInfo</span><span class="params">(AnnotatedElement element)</span> </span>&#123;</span><br><span class="line">   <span class="comment">// 找每一个标有@RequestMapping注解的方法</span></span><br><span class="line">   RequestMapping requestMapping = AnnotatedElementUtils.findMergedAnnotation(element, RequestMapping.class);</span><br><span class="line">   RequestCondition&lt;?&gt; condition = (element <span class="keyword">instanceof</span> Class ?</span><br><span class="line">         getCustomTypeCondition((Class&lt;?&gt;) element) : getCustomMethodCondition((Method) element));</span><br><span class="line">   <span class="keyword">return</span> (requestMapping != <span class="keyword">null</span> ? createRequestMappingInfo(requestMapping, condition) : <span class="keyword">null</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>自此一切就明了了，原理就是上面写的流程概述。for循环组件，找@RequestMapping注解</p>
<h3 id="小总结"><a href="#小总结" class="headerlink" title="小总结"></a>小总结</h3><p>Q：功能增强的时候什么时候用后置处理器BeanPostProcessor，什么时候用生命周期InitializingBean呢？</p>
<p>A：</p>
<ol>
<li>如果是所有组件都可能会用到的增强功能，那就实现后置处理器BeanPostProcessor来增强</li>
<li>如果是单组件增强，最好用InitializingBean。可以看到mvc的RequestMappingHandlerMapping这里用的就是InitializingBean</li>
</ol>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">youthlql</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://imlql.cn/post/6f2cef28.html">https://imlql.cn/post/6f2cef28.html</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://imlql.cn" target="_blank">风祈的时光录</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/Spring%E6%BA%90%E7%A0%81/">Spring源码</a></div><div class="post_share"></div></div><div class="post-reward"><div class="reward-button"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="https://npm.elemecdn.com/youthlql@1.0.8/blog/wechat.jpg" target="_blank"><img class="post-qr-code-img" src= "" data-lazy-src="https://npm.elemecdn.com/youthlql@1.0.8/blog/wechat.jpg" alt="微信"/></a><div class="post-qr-code-desc">微信</div></li><li class="reward-item"><a href="https://npm.elemecdn.com/youthlql@1.0.8/blog/alipay.jpg" target="_blank"><img class="post-qr-code-img" src= "" data-lazy-src="https://npm.elemecdn.com/youthlql@1.0.8/blog/alipay.jpg" alt="支付宝"/></a><div class="post-qr-code-desc">支付宝</div></li></ul></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/post/453f802e.html"><img class="prev-cover" src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/logo/spring.png" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">Spring源码系列-第10章-SpringMVC中的HandlerAdapter源码解析</div></div></a></div><div class="next-post pull-right"><a href="/post/c8dd1418.html"><img class="next-cover" src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/logo/spring.png" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">Spring源码系列-第8章-SpringMVC子容器和Spring父容器的启动原理</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/post/41fb8d9e.html" title="Spring源码系列-第2章-后置工厂处理器和Bean生命周期"><img class="cover" src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/logo/spring.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-12-21</div><div class="title">Spring源码系列-第2章-后置工厂处理器和Bean生命周期</div></div></a></div><div><a href="/post/49f419ae.html" title="Spring源码系列-第4章-Bean初始化流程"><img class="cover" src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/logo/spring.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-01-27</div><div class="title">Spring源码系列-第4章-Bean初始化流程</div></div></a></div><div><a href="/post/fb3552e0.html" title="Spring源码系列-第7章-AOP的执行流程原理和监听器原理"><img class="cover" src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/logo/spring.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-04-17</div><div class="title">Spring源码系列-第7章-AOP的执行流程原理和监听器原理</div></div></a></div><div><a href="/post/c8dd1418.html" title="Spring源码系列-第8章-SpringMVC子容器和Spring父容器的启动原理"><img class="cover" src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/logo/spring.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-06-20</div><div class="title">Spring源码系列-第8章-SpringMVC子容器和Spring父容器的启动原理</div></div></a></div><div><a href="/post/4dfb096b.html" title="Spring源码系列-第11章-SpringMVC异常处理源码和@EnableWebMvc原理"><img class="cover" src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/logo/spring.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-01-05</div><div class="title">Spring源码系列-第11章-SpringMVC异常处理源码和@EnableWebMvc原理</div></div></a></div><div><a href="/post/e3da4d66.html" title="Spring源码系列-第12章-SpringBoot源码-自动配置原理和内嵌Tomcat启动原理"><img class="cover" src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/logo/spring.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-01-06</div><div class="title">Spring源码系列-第12章-SpringBoot源码-自动配置原理和内嵌Tomcat启动原理</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content is-expand"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#%E7%AC%AC9%E7%AB%A0-SpringMVC%E8%AF%B7%E6%B1%82%E5%A4%84%E7%90%86%E6%BA%90%E7%A0%81%E5%92%8CHandlerMapping%E5%8E%9F%E7%90%86"><span class="toc-text">第9章-SpringMVC请求处理源码和HandlerMapping原理</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%AF%B7%E6%B1%82%E7%9A%84%E5%A4%84%E7%90%86%E9%93%BE%E8%B7%AF"><span class="toc-text">请求的处理链路</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#Servlet%E7%BB%A7%E6%89%BF%E6%A0%91"><span class="toc-text">Servlet继承树</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Debug%E8%B0%83%E7%94%A8%E6%A0%88"><span class="toc-text">Debug调用栈</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#DispatcherServlet-doService"><span class="toc-text">DispatcherServlet#doService()</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#DispatcherServlet-doDispatch-%E8%AF%B7%E6%B1%82%E6%B4%BE%E5%8F%91"><span class="toc-text">DispatcherServlet#doDispatch()请求派发</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#doDispatch%E5%A4%84%E7%90%86%E5%A4%A7%E6%B5%81%E7%A8%8B%E5%9B%BE"><span class="toc-text">doDispatch处理大流程图</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#DispatcherServlet-checkMultipart"><span class="toc-text">DispatcherServlet#checkMultipart()</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#StandardServletMultipartResolver-isMultipart"><span class="toc-text">StandardServletMultipartResolver#isMultipart()</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#DispatcherServlet%E4%B9%9D%E5%A4%A7%E7%BB%84%E4%BB%B6"><span class="toc-text">DispatcherServlet九大组件</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%B9%9D%E5%A4%A7%E7%BB%84%E4%BB%B6%E5%88%A9%E7%94%A8Spring%E4%BA%8B%E4%BB%B6%E6%9C%BA%E5%88%B6%E8%BF%9B%E8%A1%8C%E5%88%9D%E5%A7%8B%E5%8C%96"><span class="toc-text">九大组件利用Spring事件机制进行初始化</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#DispatcherServlet-initStrategies"><span class="toc-text">DispatcherServlet#initStrategies()</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#DispatcherServlet-initLocaleResolver"><span class="toc-text">DispatcherServlet#initLocaleResolver()</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Debug%E8%B0%83%E7%94%A8%E6%A0%88-1"><span class="toc-text">Debug调用栈</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#DispatcherServlet-onRefresh-%E6%8E%A5%E6%94%B6%E5%88%B0%E4%BA%8B%E4%BB%B6%E5%BC%80%E5%A7%8B%E5%87%86%E5%A4%87%E5%88%9D%E5%A7%8B%E5%8C%96%E4%B9%9D%E5%A4%A7%E7%BB%84%E4%BB%B6"><span class="toc-text">DispatcherServlet#onRefresh()接收到事件开始准备初始化九大组件</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#DispatcherServlet-getDefaultStrategy-%E8%8E%B7%E5%8F%96%E9%BB%98%E8%AE%A4%E5%88%9D%E5%A7%8B%E5%8C%96%E7%AD%96%E7%95%A5"><span class="toc-text">DispatcherServlet#getDefaultStrategy() 获取默认初始化策略</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#DispatcherServlet-properties"><span class="toc-text">DispatcherServlet.properties</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#HandlerMapping%E5%A4%84%E7%90%86URL%E5%92%8CController%E7%9A%84%E6%98%A0%E5%B0%84%E5%85%B3%E7%B3%BB"><span class="toc-text">HandlerMapping处理URL和Controller的映射关系</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#DispatcherServlet-doDispatch-%E8%AF%B7%E6%B1%82%E6%B4%BE%E5%8F%91-1"><span class="toc-text">DispatcherServlet#doDispatch()请求派发</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#DispatcherServlet-getHandler-%E6%A0%B9%E6%8D%AE%E8%AF%B7%E6%B1%82%E6%8B%BFController"><span class="toc-text">DispatcherServlet#getHandler()根据请求拿Controller</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#RequestMappingHandlerMapping%E5%A4%84%E7%90%86%E6%B5%81%E7%A8%8B"><span class="toc-text">RequestMappingHandlerMapping处理流程</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#AbstractHandlerMapping-getHandler-%E5%BC%80%E5%A7%8B%E6%A0%B9%E6%8D%AE%E8%AF%B7%E6%B1%82URL%E6%9F%A5%E5%93%AA%E4%B8%AAControler%E8%83%BD%E5%A4%84%E7%90%86"><span class="toc-text">AbstractHandlerMapping#getHandler()开始根据请求URL查哪个Controler能处理</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#RequestMappingInfoHandlerMapping-getHandlerInternal"><span class="toc-text">RequestMappingInfoHandlerMapping#getHandlerInternal()</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#AbstractHandlerMethodMapping-getHandlerInternal"><span class="toc-text">AbstractHandlerMethodMapping#getHandlerInternal()</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#AbstractHandlerMethodMapping-lookupHandlerMethod-%E7%9C%9F%E6%AD%A3%E6%A0%B9%E6%8D%AEURL%E6%9F%A5Controller"><span class="toc-text">AbstractHandlerMethodMapping#lookupHandlerMethod()真正根据URL查Controller</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%BF%94%E5%9B%9E%E5%88%B0AbstractHandlerMethodMapping-getHandlerInternal"><span class="toc-text">返回到AbstractHandlerMethodMapping#getHandlerInternal()</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%BF%94%E5%9B%9E%E5%88%B0AbstractHandlerMapping-getHandler"><span class="toc-text">返回到AbstractHandlerMapping#getHandler()</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#AbstractHandlerMapping-getHandlerExecutionChain-%E5%BC%80%E5%A7%8B%E6%9E%84%E9%80%A0%E5%A4%84%E7%90%86%E5%99%A8%E9%93%BE"><span class="toc-text">AbstractHandlerMapping#getHandlerExecutionChain()开始构造处理器链</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%BF%94%E5%9B%9E%E5%88%B0DispatcherServlet-getHandler"><span class="toc-text">返回到DispatcherServlet#getHandler()</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%BF%94%E5%9B%9E%E5%88%B0DispatcherServlet-doDispatch"><span class="toc-text">返回到DispatcherServlet#doDispatch()</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#RequestMappingHandlerMapping%E5%A6%82%E4%BD%95%E4%BF%9D%E5%AD%98%E6%98%A0%E5%B0%84%E5%85%B3%E7%B3%BB"><span class="toc-text">RequestMappingHandlerMapping如何保存映射关系</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#AbstractHandlerMethodMapping-registerMapping"><span class="toc-text">AbstractHandlerMethodMapping#registerMapping()</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#MappingRegistry-URL-gt-XXXController%E7%9A%84%E6%98%A0%E5%B0%84%E4%B8%AD%E5%BF%83"><span class="toc-text">MappingRegistry(URL&#x3D;&gt;XXXController的映射中心)</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Debug%E8%B0%83%E7%94%A8%E6%A0%88-2"><span class="toc-text">Debug调用栈</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%B5%81%E7%A8%8B%E6%A6%82%E8%BF%B0"><span class="toc-text">流程概述</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#RequestMappingHandlerMapping-afterPropertiesSet"><span class="toc-text">RequestMappingHandlerMapping#afterPropertiesSet()</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#AbstractHandlerMethodMapping-afterPropertiesSet"><span class="toc-text">AbstractHandlerMethodMapping#afterPropertiesSet()</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#AbstractHandlerMethodMapping-initHandlerMethods-%E5%88%9D%E5%A7%8B%E5%8C%96HandlerMethods"><span class="toc-text">AbstractHandlerMethodMapping#initHandlerMethods()初始化HandlerMethods</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#AbstractHandlerMethodMapping-processCandidateBean"><span class="toc-text">AbstractHandlerMethodMapping#processCandidateBean()</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#RequestMappingHandlerMapping-isHandler-%E5%88%A4%E6%96%AD%E5%BD%93%E5%89%8Dbean%E6%98%AF%E4%B8%8D%E6%98%AFHandler"><span class="toc-text">RequestMappingHandlerMapping#isHandler()判断当前bean是不是Handler</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#AbstractHandlerMethodMapping-detectHandlerMethods-%E6%8E%A2%E6%9F%A5%E5%AE%B9%E5%99%A8%E9%87%8C%E6%BB%A1%E8%B6%B3%E6%9D%A1%E4%BB%B6%E7%9A%84%E6%96%B9%E6%B3%95"><span class="toc-text">AbstractHandlerMethodMapping#detectHandlerMethods()探查容器里满足条件的方法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#RequestMappingHandlerMapping-getMappingForMethod"><span class="toc-text">RequestMappingHandlerMapping#getMappingForMethod()</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#RequestMappingHandlerMapping-createRequestMappingInfo-AnnotatedElement"><span class="toc-text">RequestMappingHandlerMapping#createRequestMappingInfo(AnnotatedElement )</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%B0%8F%E6%80%BB%E7%BB%93"><span class="toc-text">小总结</span></a></li></ol></li></ol></li></ol></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2023 By youthlql</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text"><a href="https://www.upyun.com/?utm_source=lianmeng&utm_medium=referral" target="_blank" rel="noopener" class="one-pan-link-mark"><img style="position:relative;top:-3px; " src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/upyun/logo.png" align="absmiddle" width="60px" height="30px"></a><a target="_blank" rel="noopener" href="https://beian.miit.gov.cn"><img class="icp-icon" src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/logo/icp.png"><span>鄂ICP备19028890号</span></a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">简</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">本地搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div></div></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://npm.elemecdn.com/@fancyapps/ui/dist/fancybox.umd.js"></script><script src="https://npm.elemecdn.com/instant.page/instantpage.js" type="module"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="/js/search/local-search.js"></script><div class="js-pjax"></div><script defer src="https://npm.elemecdn.com/jquery@latest/dist/jquery.min.js"></script></div></body></html>